package com.javacoo.swing.jxbrowser.content;

import java.awt.BorderLayout;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import com.javacoo.swing.jxbrowser.BaseBrowser;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserContext;
import com.teamdev.jxbrowser.chromium.ProtocolHandler;
import com.teamdev.jxbrowser.chromium.ProtocolService;
import com.teamdev.jxbrowser.chromium.URLRequest;
import com.teamdev.jxbrowser.chromium.URLResponse;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

/**
 * 自定义协议处理程序
 * <li></li>
 *  xBrowser 6.11及更高版本提供了API，允许您处理标准（例如HTTP，HTTPS，FTP等）和非标准（例如JAR，MYPROTOCOL等）协议的URL请求。以下示例演示如何为标准HTTPS协议注册协议处理程序以及如何使用自定义数据进行响应
 *
 *  您可以使用相同的方法来处理自定义的非标准协议（例如“teamdev”）
 *
 *  也可以为JAR协议注册自定义协议处理程序。它允许您直接从包含在应用程序类路径中的JAR库加载HTML文件
 * @author: duanyong@jccfc.com
 * @since: 2020/9/27 9:10
 */
public class CustomProtocolHandler extends BaseBrowser {
    // public static void main(String[] args) {
    //     Browser browser = new Browser();
    //     BrowserView view = new BrowserView(browser);
    //
    //     JFrame frame = new JFrame();
    //     frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    //     frame.add(view, BorderLayout.CENTER);
    //     frame.setSize(700, 500);
    //     frame.setLocationRelativeTo(null);
    //     frame.setVisible(true);
    //
    //     BrowserContext browserContext = browser.getContext();
    //     ProtocolService protocolService = browserContext.getProtocolService();
    //     protocolService.setProtocolHandler("https", new ProtocolHandler() {
    //         @Override
    //         public URLResponse onRequest(URLRequest request) {
    //             URLResponse response = new URLResponse();
    //             String html = "<html><body><p>Hello there!</p></body></html>";
    //             response.setData(html.getBytes());
    //             response.getHeaders().setHeader("Content-Type", "text/html");
    //             return response;
    //         }
    //     });
    //
    //     browser.loadURL(BASE_URL);
    // }

    // public static void main(String[] args) {
    //     Browser browser = new Browser();
    //     BrowserView view = new BrowserView(browser);
    //
    //     JFrame frame = new JFrame();
    //     frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    //     frame.add(view, BorderLayout.CENTER);
    //     frame.setSize(700, 500);
    //     frame.setLocationRelativeTo(null);
    //     frame.setVisible(true);
    //
    //     BrowserContext browserContext = browser.getContext();
    //     ProtocolService protocolService = browserContext.getProtocolService();
    //     protocolService.setProtocolHandler("teamdev", new ProtocolHandler() {
    //         @Override
    //         public URLResponse onRequest(URLRequest request) {
    //             URLResponse response = new URLResponse();
    //             String html = "<html><body><p>Hello there!</p></body></html>";
    //             response.setData(html.getBytes());
    //             response.getHeaders().setHeader("Content-Type", "text/html");
    //             return response;
    //         }
    //     });
    //
    //     browser.loadURL("teamdev://custom-request/");
    // }

    public static void main(String[] args) {
        final Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        BrowserContext browserContext = browser.getContext();
        ProtocolService protocolService = browserContext.getProtocolService();
        protocolService.setProtocolHandler("jar", new ProtocolHandler() {
            @Override
            public URLResponse onRequest(URLRequest request) {
                try {
                    URLResponse response = new URLResponse();
                    URL path = new URL(request.getURL());
                    InputStream inputStream = path.openStream();
                    DataInputStream stream = new DataInputStream(inputStream);
                    byte[] data = new byte[stream.available()];
                    stream.readFully(data);
                    response.setData(data);
                    String mimeType = getMimeType(path.toString());
                    response.getHeaders().setHeader("Content-Type", mimeType);
                    return response;
                } catch (Exception ignored) {}
                return null;
            }
        });

        // Assume that we need to load a resource related to this class in the JAR file
        browser.loadURL(CustomProtocolHandler.class.getResource("index.html").toString());
    }

    private static String getMimeType(String path) {
        if (path.endsWith(".html")) {
            return "text/html";
        }
        if (path.endsWith(".css")) {
            return "text/css";
        }
        if (path.endsWith(".js")) {
            return "text/javascript";
        }
        return "text/html";
    }
}
